import jwt from 'jsonwebtoken';
import { UserModel } from '../../schemas/system/User'
// import { RoleModel } from '../../schemas/system/Role';
import { RegisterDto, LoginDto } from '../../dtos/system/UserDto';
import { HttpError } from '../../exceptions/HttpError';
import { envConfig } from '../../config/environment';
import { log } from '../../config/logger';
export interface AuthResponse {
  user: any;
  token: string;
}

export class AuthService {
  // 生成 JWT Token
  #generateToken(userId: string): string {
    return jwt.sign(
      { userId },
      envConfig.jwtSecret,
      { expiresIn: '7d' }
    );
  }

  // 用户注册
  async register(registerDto: RegisterDto): Promise<AuthResponse> {
    try {
      // 检查用户是否已存在
      const existingUser = await UserModel.findOne({ email: registerDto.email });
      if (existingUser) {
        log.warn(`注册失败: 邮箱已存在 - ${registerDto.email}`);
        throw new Error('邮箱已存在');
      }
    
      // 创建新用户
      const user = new UserModel({
        name: registerDto.name,
        email: registerDto.email,
        password: registerDto.password,

      });

      await user.save();

      // 生成 JWT token
      const token = this.#generateToken((user._id as any).toString());

      log.info(`用户注册成功: ${user.email} (${user.roles})`);

      return {
        user: {
          id: (user._id as any).toString(),
          name: user.name,
          email: user.email,
        },
        token
      };
    } catch (error) {
      log.error('注册错误:', error);
      throw error;
    }
  }

  // 用户登录
  async login(loginDto: LoginDto): Promise<AuthResponse> {
    try {

      const user = await UserModel.findOne({ email: loginDto.email }).populate('roles');
      if (!user) {
        log.warn(`登录失败: 用户不存在 - ${loginDto.email}`);
        throw new Error('用户不存在');
      }

      // 验证密码
      const isPasswordValid = await (user as any).comparePassword(loginDto.password);
      if (!isPasswordValid) {
        log.warn(`登录失败: 密码错误 - ${loginDto.email}`);
        throw new Error('密码错误');
      }

      // 生成 JWT token
      const token = this.#generateToken((user._id as any).toString());
      // 更新用户最后登录时间
      user.lastLogin = new Date();
      await user.save();

      log.info(`用户登录成功: ${user.email} (${user.roles})`);

      return {
        user: {
          id: (user._id as any).toString(),
          name: user.name,
          email: user.email,
          roles: user.roles
        },
        token
      };
    } catch (error) {
      log.error('登录错误:', error);
      throw error;
    }
  }

  // 验证 token
  async verifyToken(token: string): Promise<any> {
    try {
      const decoded = jwt.verify(token, envConfig.jwtSecret) as { userId: string };
      const user = await UserModel.findById(decoded.userId).select('-password').populate('roles');
      if (!user) {
        throw HttpError.unauthorized('用户不存在');
      }
      const isValid = await (user as any).verifyIsActive();
      if (!isValid) {
        throw HttpError.forbidden('账户已被禁用');
      }

      return user;
    } catch (error: any) {
      console.log(error, 'error')
      if (error instanceof HttpError) throw error;
      if (error.name === 'JsonWebTokenError') {
        throw HttpError.unauthorized('无效的 token');
      }
      if (error.name === 'TokenExpiredError') {
        throw HttpError.unauthorized('token 已过期');
      }
      throw HttpError.unauthorized('token 验证失败');
    }
  }

  // 刷新 token
  async refreshToken(userId: string): Promise<string> {
    try {
      const user = await UserModel.findById(userId);
      if (!user || !user.isActive) {
        throw HttpError.unauthorized('用户不存在或已被禁用');
      }

      return this.#generateToken(userId);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`刷新 token 失败: ${error.message}`);
    }
  }
}

export default AuthService;